package com.gpj.learn.springcloud.ribbon.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * @className CustomLoadBalancerRule
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/9/28 16:25
 * @version 1.0
 **/
@Slf4j
public class CustomLoadBalancerRule extends AbstractLoadBalancerRule {
	private static final String METADATA_GPJ_KEY = "gpj";

	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;

	@Override
	public Server choose(Object key) {
		DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
		String serviceName = loadBalancer.getName();
		NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
		try {
			Map<String, String> selfMetadata = nacosDiscoveryProperties.getMetadata();
			List<Instance> allInstances = namingService.getAllInstances(serviceName);
			for (Instance instance : allInstances) {
				Map<String, String> metadata = instance.getMetadata();

				if(StringUtils.equals(selfMetadata.get(METADATA_GPJ_KEY), metadata.get(METADATA_GPJ_KEY))){
					return new NacosServer(instance);
				}
			}
			return new NacosServer(allInstances.get(0));
		} catch (NacosException e) {
			log.error("获取服务实例异常：{}", e.getMessage(), e);
		}
		return null;
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {

	}
}
